#include "stm32f10x.h"                  // Device header
#include <stdio.h>
#include "SHT40.h"
#include "ESP8266.h"
#include "GreeAircon.h"
#include "Serial.h"
#include "OLED.h"
#include "Delay.h"

void ReportDataToPanel(void) {
	char buf[64];
	sprintf(buf,"<0%3d%2d>",(int)(SHT40_GetTemperature()*10),(int)SHT40_GetHumidity());
	ESP8266_SendCIPMessage(buf);
}

unsigned char setTemp=25,setFan=0;
void handleCommand(unsigned char code,unsigned char *data) {
	switch(code) {
		case 0:
			GreeAircon_Off();
		  OLED_ShowString(4,6,"Air Off");
			break;
		case 1:
			setTemp = (data[0]&0x0f)*10 + (data[1]&0x0f);
		  setFan = data[2]&0x0f;
			OLED_ShowString(4,6,"Air On ");
			GreeAircon_SetStatus(setTemp,setFan);
			break;
	}
}

void checkAndParsePanelCommand(void) {
	if(!Serial_GetRxFlag())
			return;
	char ackBuf[32];
	char *ackBufP = ackBuf;
	unsigned char *start = Serial_GetRxString();
	unsigned char *stop;
  while(*start !=0) {
        stop = start+1;
        if (*start == '<' && start[1] == '(' && start[2] != 0) {
            stop = start + 3;
            while(*stop != 0) {
                if (*stop == ')' && stop[1] =='>') {
										handleCommand(start[2] & 0x0f,start+3);
									  do{
											start++;
											*ackBufP = *start;
											ackBufP++;
										}while(start != stop);
										*ackBufP = 0;
										ESP8266_SendCIPMessage(ackBuf); //向主机发送确认收到
                    start += 3; //此时start指向data第一位，而stop指向）
                    start = stop+1;
										break;
                }
                stop++;
            }
        }
        start++;
    }
	Serial_ClearRxString();
}

void MainLoop(void) {
	int loop = 0;
	while(1) {
		if(loop == 50) {
			SHT40_Measure();
			OLED_ShowNum(3,1,(int)SHT40_GetTemperature(),4);
			OLED_ShowNum(3,6,(int)SHT40_GetHumidity(),4);
			ReportDataToPanel(); //5秒测一次温湿度并上报服务器
			loop = 0;
		} else {
			OLED_ShowNum(4,1,setTemp,2);
			OLED_ShowNum(4,4,setFan,1);
			checkAndParsePanelCommand();
			loop ++; //每100ms检查服务器是否有指令发来
		}
		Delay_ms(100);
	}
}
